<template>
  <div id="share-order">
    <md-result-page v-if="orderStatus=='6'" class="customized" :img-url="require('@/assets/imgs/shareorder_canceled_img.png')" text="当前行程已取消"></md-result-page>
    <md-result-page v-if="orderStatus=='5'||orderStatus=='7'" class="customized" :img-url="require('@/assets/imgs/shareorder_finish_img.png')" text="当前行程已结束"></md-result-page>
    <div class="container column" v-if="orderStatus!='5'&&orderStatus!='6'&&orderStatus!='7'">
      <div class="info-panel column">
        <div class="row driver-info" v-if="getShareOrderInfo&&getShareOrderInfo.order_status != '0'&&getShareOrderInfo.driverName">
          <div class="driver-head">
            <img :src="getShareOrderInfo.driver_photo==''?defaultDriverImage:getShareOrderInfo.driver_photo" />
          </div>
          <div class="column around" style="margin-left: 22px">
            <div class="row centered">
              <div class="driver-name">{{getShareOrderInfo.driverName}}</div>
              <!-- <rate class="mx-2" v-model="getShareOrderInfo.driver_level" readonly></rate>
              <div style="font-size:20px;color:#FF6917">{{getShareOrderInfo.driver_level}}</div>-->
            </div>
            <div class="row">
              <div style="color:#666666;font-size:26px;margin-right:20px">{{getShareOrderInfo.driver_car}}</div>
              <div style="color:#999999;font-size:26px">{{getShareOrderInfo.car_color}}·</div>
              <div style="color:#999999;font-size:26px">{{getShareOrderInfo.car_info}}</div>
            </div>
          </div>
        </div>
        <div class="order-info column">
          <div class="row centered">
            <md-icon class="icon" name="time"></md-icon>
            <div class="time-str mx-2">{{startTime}}</div>
            <div class="mode-str">
              <span>{{tripType}}</span>
            </div>
          </div>
          <div class="row centered my-1">
            <md-icon class="icon" name="shangchedian"></md-icon>
            <div class="time-str mx-2">{{getShareOrderInfo?getShareOrderInfo.start_route_desc:''}}</div>
          </div>
          <div class="row centered">
            <md-icon class="icon" name="xiachedian"></md-icon>
            <div class="time-str mx-2">{{getShareOrderInfo?getShareOrderInfo.end_route_desc:''}}</div>
          </div>
        </div>
      </div>
      <amap ref="map" class="map-tool" @complete="onMapComplete"></amap>
    </div>
    <div class="shareordertip" v-if="orderStatus!='5'&&orderStatus!='6'&&orderStatus!='7'">
      <p @click="refreshBtn">
        <md-icon class="shareordertipicon" name="shuaxin"></md-icon>
      </p>
      <p @click="callService">
        <md-icon class="shareordertipicon" name="snyc_more_lxkf"></md-icon>
      </p>
    </div>
  </div>
</template>

<script>
import '@/assets/svgs/time.svg';
import '@/assets/svgs/shangchedian.svg';
import '@/assets/svgs/xiachedian.svg';
import '@/assets/svgs/snyc_more_lxkf.svg';
import '@/assets/svgs/shuaxin.svg';
import MapTool from '@/components/map/MapTool';
import Rate from '@/components/Rate';
import { mapGetters } from 'vuex';
import { ResultPage, Icon, Dialog } from 'mand-mobile';
import { DRIVER_IN_ALLOT_TOPIC, DRIVER_POSITION_TOPIC } from '@/store/mqtt.topics';
import {
  INCITY_STATUS_ORDERING,
  INCITY_STATUS_STANDBY,
  INCITY_STATUS_PICKING,
  INCITY_STATUS_ARRIVED,
  INCITY_STATUS_TRAVELLING,
  INCITY_STATUS_FINISHED,
  INCITY_STATUS_CANCELD,
  INCITY_STATUS_CLOSED
} from './types';
import { decryptByDESModeEBC, encryptByDESModeEBC } from '@/common/encrypt';
const MARKER_MOVE_SPEED = 45;
const moment = require('moment');
moment.locale('zh_cn');
export default {
  name: 'share-order',
  components: {
    [ResultPage.name]: ResultPage,
    [MapTool.name]: MapTool,
    [Icon.name]: Icon,
    [Rate.name]: Rate
  },
  data() {
    return {
      mapInstance: null,
      orderNo: undefined,
      orderStatus: '0',
      drverPosition: undefined,
      car: null,
      line: null,
      currentRouteLine: null,
      currentRoutePositions: null,
      currentTopic: undefined,
      mqttInited: false,
      textMarker: null,
      currentInfoWindow: null,
      hasNavigator: false
    };
  },
  created() {
    this.orderNo = this.$route.query.orderno;
    this.type = this.$route.query.type;
    let params = {
      order_no: this.orderNo,
      type: this.type
    };
    if (this.orderNo) {
      this.$store
        .dispatch('getShareTaxiOrderInfo', params)
        .then(() => {
          if (this.getShareOrderInfo && this.mapInstance) {
            this.init();
          }
        })
        .catch(reason => {
          this.orderStatus = '8';
        });
    }
  },
  methods: {
    // 刷新页面
    refreshBtn() {
      if (this.mapInstance) {
        this.$refs.map.removePathNavigator();
        this.mapInstance.clearMap();
      }
      let params = {
        order_no: this.orderNo,
        type: this.type
      };
      if (this.orderNo) {
        this.$store
          .dispatch('getShareTaxiOrderInfo', params)
          .then(() => {
            if (this.getShareOrderInfo && this.mapInstance) {
              this.init();
            }
          })
          .catch(reason => {
            this.orderStatus = '8';
          });
      }
    },
    onMapComplete(map) {
      this.mapInstance = map;
      if (this.getShareOrderInfo && this.mapInstance) {
        this.init();
        if (process.env.NODE_ENV === 'development') {
          this.initEmulator();
        }
      }
    },
    init() {
      console.log('当前出租车订单数据：', this.getShareOrderInfo);
      this.orderStatus = this.getShareOrderInfo.order_status;
      let startCoord = this.getShareOrderInfo.start_route_coord.split(',');
      this.getShareOrderInfo.start_route_coord = new AMap.LngLat(startCoord[0], startCoord[1]);
      let destCoord = this.getShareOrderInfo.end_route_coord.split(',');
      this.getShareOrderInfo.end_route_coord = new AMap.LngLat(destCoord[0], destCoord[1]);
      // 根据订单状态切换不用的UI显示内容
      switch (this.orderStatus) {
        case INCITY_STATUS_ORDERING:
          this.Ordering();
          break; // 待派单
        case INCITY_STATUS_STANDBY:
          this.Standby();
          break; // 待接驾
        case INCITY_STATUS_PICKING:
          this.Picking();
          this.initMqtt();
          break; // 接驾中
        case INCITY_STATUS_ARRIVED:
          this.Picking();
          this.initMqtt();
          break;
        case INCITY_STATUS_TRAVELLING:
          this.Travelling();
          this.initMqtt();
          break; // 行程中
        case INCITY_STATUS_FINISHED:
          this.Finished();
          break; // 已完成
        case INCITY_STATUS_CANCELD:
          this.Cancelled();
          break; // 已取消
        case INCITY_STATUS_CLOSED:
          this.Finished();
          break;
      }
    },
    Ordering() {
      // 待派单
      console.log('当前订单状态：待派单');
      this.showStartMarker();
      this.showDestMarkder();
      this.mapInstance.setFitView();
      this.showTextMarker('等待系统派单', this.getShareOrderInfo.start_route_coord);
    },
    Standby() {
      // 待接驾
      console.log('当前订单状态：待接驾');
      this.showStartMarker();
      this.mapInstance.setFitView();
      this.showTextMarker('在这里上车', this.getShareOrderInfo.start_route_coord);
    },
    Finished() {
      // 已完成
      console.log('当前订单状态：已完成');
    },
    Cancelled() {
      // 已取消
      console.log('当前订单状态：已取消');
    },
    Travelling() {
      // 行程中
      console.log('当前订单状态：行程中');
      this.showStartMarker();
      this.showDestMarkder();
      if (this.getShareOrderInfo.path) {
        if (this.getShareOrderInfo.path.length > 0) {
          this.$refs.map
            .createPathNavigator(
              this.getShareOrderInfo.path[this.getShareOrderInfo.path.length - 1],
              this.getShareOrderInfo.end_route_coord
            )
            .then(() => {
              this.$refs.map.updateDriveCar(this.getShareOrderInfo.path[this.getShareOrderInfo.path.length - 1]);
              this.mapInstance.setFitView();
              this.hasNavigator = true;
            });
        }
      }
    },
    Picking() {
      // 接驾中
      console.log('当前订单状态：接驾中');
      this.currentRoutePositions = [];
      this.showStartMarker();
      if (this.getShareOrderInfo.path) {
        if (this.getShareOrderInfo.path.length > 0) {
          this.$refs.map
            .createPathNavigator(
              this.getShareOrderInfo.path[this.getShareOrderInfo.path.length - 1],
              this.getShareOrderInfo.start_route_coord
            )
            .then(() => {
              this.$refs.map.updateDriveCar(this.getShareOrderInfo.path[this.getShareOrderInfo.path.length - 1]);
              this.mapInstance.setFitView();
              this.hasNavigator = true;
            });
        }
      }
    },
    showStartMarker() {
      let startMarker = new AMap.Marker({
        map: this.mapInstance,
        position: this.getShareOrderInfo.start_route_coord,
        offset: new AMap.Pixel(-10, -24),
        icon: new AMap.Icon({
          size: new AMap.Size(40, 48), // 图标尺寸
          image: process.env.BASE_URL + 'static/imgs/snyc_shangche_icon.png',
          imageSize: new AMap.Size(20, 24) // 根据所设置的大小拉伸或压缩图片
        })
      });
      let textMarker = new AMap.Text({
        map: this.mapInstance,
        position: this.getShareOrderInfo.start_route_coord,
        text: '<div class="map-location-name">' + this.getShareOrderInfo.start_route_desc + '</div>',
        style: {
          border: '0px',
          background: 'transparent',
          height: '35px'
        },
        offset: new AMap.Pixel(0, 15)
      });
    },
    showDestMarkder() {
      let destMarker = new AMap.Marker({
        map: this.mapInstance,
        position: this.getShareOrderInfo.end_route_coord,
        offset: new AMap.Pixel(-10, -24),
        icon: new AMap.Icon({
          size: new AMap.Size(40, 48), // 图标尺寸
          image: process.env.BASE_URL + 'static/imgs/snyc_xiache_icon.png',
          imageSize: new AMap.Size(20, 24) // 根据所设置的大小拉伸或压缩图片
        })
      });
      let textMarker = new AMap.Text({
        map: this.mapInstance,
        position: this.getShareOrderInfo.end_route_coord,
        text: '<div class="map-location-name">' + this.getShareOrderInfo.end_route_desc + '</div>',
        style: {
          border: '0px',
          background: 'transparent',
          height: '35px'
        },
        offset: new AMap.Pixel(0, 15)
      });
    },
    showTextMarker(string, position) {
      let textMarker = new AMap.Text({
        map: this.mapInstance,
        bubble: false,
        text: '<div class="map-shareorder-infowindow">' + string + '</div>',
        position: position,
        textAlign: 'center',
        verticalAlign: 'middle',
        style: {
          border: '0px',
          background: 'transparent',
          height: '35px'
        },
        clickable: false,
        offset: new AMap.Pixel(-5, -40)
      });
    },
    hideStartMarker() {
      if (this.startMarker) {
        this.startMarker.hide();
      }
    },
    hideDestMarker() {
      if (this.destMarker) {
        this.destMarker.hide();
      }
    },
    /**
     * 拨打紧急电话
     */
    callService() {
      if (this.getShareOrderInfo.service_phone) {
        Dialog.confirm({
          content: '客服电话：' + this.getShareOrderInfo.service_phone,
          confirmText: '拨打电话',
          onConfirm: () => {
            window.open('tel:' + this.getShareOrderInfo.service_phone);
          }
        });
      }
    },
    initMqtt() {
      if (this.mqttClient) {
        if (this.mqttConnected) {
          return;
        }
      }
      this.$store
        .dispatch('getMqttConfig')
        .then(() => {
          // 获取MQTT配
          if (this.mqttConfig) {
            this.$store.dispatch('initMqttClient', this.mqttConfig).then(() => {
              // 链接MQTT
              this.mqttInited = true;
              this.mqttClient.onMessageArrived = this.onMessageArrive;
              this.mqttClient.onConnectionLost = this.onMqttLost;
              let topic = DRIVER_IN_ALLOT_TOPIC + this.getShareOrderInfo.allotId + '/';
              this.$store.dispatch('subscribe', topic).then(() => {
                this.currentTopic = topic;
              });
            });
          }
        })
        .catch(reason => {
          console.error('无法获取MQTT配置');
        });
    },
    onMessageArrive(message) {
      console.log(message);
      let str = message.payloadString;
      let resultStr = decryptByDESModeEBC(str);
      let result = JSON.parse(resultStr);
      if (result.position) {
        let positionStr = decryptByDESModeEBC(result.position);
        if (!this.hasNavigator) {
          this.$store.commit('setShareOrderInfoPath', [positionStr]);
          this.init();
        }
        this.$refs.map.updateDriveCar(positionStr.split(','));
      }
    },
    onMqttLost(response) {
      console.error('MQTT连接丢失，这有可能是消息内部处理出错!');
    },
    initEmulator() {
      this.mapInstance.on('click', e => {
        if (!this.currentTopic) {
          return;
        }
        let body = {
          position: encryptByDESModeEBC(e.lnglat.lng + ',' + e.lnglat.lat)
        };
        let jsonStr = JSON.stringify(body);
        let encryptdStr = encryptByDESModeEBC(jsonStr);
        let message = {
          topic: this.currentTopic,
          msg: encryptdStr
        };
        this.$store.commit('sendMqttMessage', message);
      });
    }
  },
  computed: {
    ...mapGetters(['getShareOrderInfo', 'mqttConfig', 'mqttClient', 'mqttConnected']),
    startTime() {
      let str = '';
      if (this.getShareOrderInfo) {
        let mom = moment(this.getShareOrderInfo.start_time, 'x');
        str = mom.calendar(null, {
          sameDay: '[今天] HH:mm',
          nextDay: '[明天] HH:mm',
          nextWeek: 'dddd HH:mm',
          lastDay: '[昨天] HH:mm',
          lastWeek: '[上] ddd HH:mm',
          sameElse: 'MMMDo HH:mm'
        });
      }
      return str;
    },
    tripType() {
      var type = '';
      if (this.getShareOrderInfo) {
        type = this.getShareOrderInfo.order_desc.split('-')[0];
      }
      return type;
    },
    tripNumber() {
      var number = '';
      if (this.getShareOrderInfo) {
        number = this.getShareOrderInfo.order_desc.split('-')[1];
      }
      return number;
    }
  }
};
</script>

<style lang="stylus">
#share-order {
  .customized {
    margin-top: 260px;

    img {
      width: 278px;
      height: 188px;
    }

    .text {
      font-size: 28px;
      font-weight: 500;
      color: color-text-minor;
      line-height: 40px;
    }
  }

  .container {
    .info-panel {
      position: absolute;
      top: 0;
      background-color: #fff;
      z-index: 300;
      padding: 28px 10px 28px 30px;
      box-shadow: 0px 2px 8px 0px rgba(191, 191, 191, 0.5);
      width: 100vw;
      box-sizing: border-box;

      .driver-info {
        border-bottom: 1px solid #efefef;
        padding-bottom: 20px;

        .driver-head {
          width: 100px;
          height: 100px;
          border-radius: 50%;
          border: 0px solid #eee;
          overflow: hidden;

          img {
            width: 100%;
            height: 100%;
            object-fit: cover;
          }
        }

        .driver-name {
          font-size: 30px;
        }
      }

      .order-info {
        margin-top: 20px;

        .icon {
          width: 16px;
          height: 16px;
        }

        .time-str {
          font-size: 24px;
          color: rgba(102, 102, 102, 1);
          line-height: 34px;
          min-width: 3em;
          max-width: 22em;
          white-space: nowrap;
          overflow: hidden;
          text-overflow: ellipsis;
        }

        .mode-str span {
          border-radius: 6px;
          border: 1px solid rgba(224, 224, 224, 1);
          font-size: 20px;
          color: rgba(153, 153, 153, 1);
          text-align: center;
          vertical-align: middle;
          padding: 2px 10px;
        }

        .number-str {
          border-radius: 6px;
          border: 1px solid rgba(224, 224, 224, 1);
          font-size: 20px;
          color: rgba(153, 153, 153, 1);
          text-align: center;
          vertical-align: middle;
          display: table-cell;
          padding: 0px 10px;
        }
      }
    }
  }

  .shareordertip {
    position: absolute;
    right: 20px;
    bottom: 20px;
  }

  .shareordertip p {
    margin-top: 10px;
  }

  .shareordertipicon {
    width: 84px;
    height: 84px;
  }
}
</style>
